package com.wl.rjwmc.Utools;

import com.alibaba.fastjson2.JSON;
import com.wl.rjwmc.Config.BaseContext;
import lombok.extern.slf4j.Slf4j;

import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//网页拦截器 拦截非正规进入用户
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
//拦截有地址
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        response.setCharacterEncoding("utf-8");
//       防止乱码
        String uri = request.getRequestURI();
//        获取请求的URI
        String[] urls  = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
//        不需要拦截的地址
        boolean flag =check(urls,uri);
        if(flag){
            filterChain.doFilter(request,response);
            return;
        }
//    判断登录状态，如果已登录，则直接放⾏
        if(request.getSession().getAttribute("employee")!=null){

            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
//            多线程（获取id）
            filterChain.doFilter(request,response);
            return;
        }

        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

//        5、如果未登录则返回未登录结果，通过输出流⽅式向客户端⻚⾯响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
    private boolean check(String[] urls,String uri){
        for (String url : urls){
            if (PATH_MATCHER.match(url,uri)){
                return true;
            }
        }
        return false;
    }
}
